<?php
require_once 'Door.php';
/**
 * Passage class, exits data.
 * @package space
 * @author alcaitiff
 */
class Passage extends ExportableObject 
{
    /**
     *
     * @var Room
     */
    private $roomTo;
    /**
     *
     * @var Room
     */
    private $roomFrom;
    /**
     *
     * @var string
     */
    private $originalDirection;
    /**
     *
     * @var string
     */
    protected $direction;
    /**
     *
     * @var Door 
     */
    protected $door;

    /**
     *
     * @param string $dir Direction
     * @param int $door Door id
     */
    public function __construct($dir,$door){
        $this->direction = $dir;
        $this->door = new Door($door);
	}
    /**
     * Lock the passage door
     * @return void
     */
    public function lock($char){
        if($this->door->lock($char))
            $this->broadCast($char->charId.' locked door ',$char);
    }
    /**
     * Unlock the passage door
     * @return void
     */
    public function unlock($char){
        if($this->door->unlock($char))
            $this->broadCast($char->charId.' unlocked door ',$char);
    }
    /**
     * Open the passage door
     * @return void
     */
    public function open($char){
        if($this->door->open())
            $this->broadCast($char->charId.' open door ',$char);
    }
    /**
     * Close the passage door
     * @return void
     */
    public function close($char){
        if($this->door->close())
            $this->broadCast($char->charId.' close door ',$char);
    }
    /**
     * Send a message to all characters in two rooms
     * @param Char $char
     * @param string $message
     * @return void
     */
    private function broadCast($message,$char){
        $this->retrieveData();
        if($this->direction!=$this->originalDirection){
            $aux=$this->roomTo;
            $this->roomTo=$this->roomFrom;
            $this->roomFrom=$aux;
        }
        $this->roomFrom->broadcastMessage($message.$this->direction, $char);
        $this->roomTo->broadcastMessage($message.Room::reverseDir($this->direction), $char);
    }
    //***********************************************************************************************************
    //					DATABASE METHODS
    //***********************************************************************************************************
    /**
     * Retrieve DB data
     * @return void
     */
    private function retrieveData(){
        $dbo=new DB();
		$db=$dbo->db;
		$stmt = $db->prepare(	'SELECT `room_from`, `room_to`, `direction`'.
								'FROM `passages` '.
								'WHERE  door = ? '
								);
	    $id=$this->door->getId();
        $stmt->bind_param("i", $id);
	    $stmt->bind_result($from,$to,$this->originalDirection);
	    $stmt->execute();
	    $stmt->fetch();
        $this->roomFrom=new Room($from);
        $this->roomTo=new Room($to);
  		$stmt->close();
    }
}